<template>
  <div class="permission-management">
    <h2>{{ $t('message.permissionManagement') }}</h2>
    
    <div class="permission-actions">
      <el-button type="primary" @click="openAddPermissionDialog">{{ $t('message.addPermission') }}</el-button>
    </div>
    
    <el-table
      :data="permissions"
      style="width: 100%"
    >
      <el-table-column prop="permissionName" :label="$t('message.permissionName')" width="200" align="left" header-align="left" />
      <el-table-column prop="permissionCode" :label="$t('message.permissionCode')" width="200" align="left" header-align="left" />
      <el-table-column prop="permissionDescription" :label="$t('message.description')" show-overflow-tooltip align="left" header-align="left" />
      <el-table-column :label="$t('message.actions')" width="200" align="left" header-align="left">
        <template #default="scope">
          <el-button size="small" @click="editPermission(scope.row)">{{ $t('message.edit') }}</el-button>
          <el-button size="small" type="danger" @click="deletePermission(scope.row.permissionId)">{{ $t('message.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加/编辑权限对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="permissionForm" :rules="permissionRules" ref="permissionFormRef" label-width="120px">
        <el-form-item :label="$t('message.permissionName')" prop="permissionName">
          <el-input v-model="permissionForm.permissionName"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.permissionCode')" prop="permissionCode">
          <el-input v-model="permissionForm.permissionCode"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.description')" prop="permissionDescription">
          <el-input 
            v-model="permissionForm.permissionDescription" 
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t('message.cancel') }}</el-button>
          <el-button type="primary" @click="savePermission">{{ $t('message.confirm') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores/auth';

export default {
  name: 'PermissionManagement',
  setup() {
    const { t } = useI18n();
    const authStore = useAuthStore();
    
    // 权限数据
    const permissions = ref([]);
    
    // 对话框相关
    const dialogVisible = ref(false);
    const dialogTitle = ref('');
    const isEdit = ref(false);
    
    // 表单数据
    const permissionForm = ref({
      permissionId: '',
      permissionName: '',
      permissionCode: '',
      permissionDescription: ''
    });
    
    const permissionFormRef = ref();
    
    // 表单验证规则
    const permissionRules = {
      permissionName: [
        { required: true, message: t('message.pleaseEnterPermissionName'), trigger: 'blur' }
      ],
      permissionCode: [
        { required: true, message: t('message.pleaseEnterPermissionCode'), trigger: 'blur' }
      ]
    };
    
    // 获取权限列表
    const loadPermissions = async () => {
      try {
        const response = await fetch('/api/admin/permissions', {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          permissions.value = await response.json();
        } else {
          ElMessage.error(t('message.failedToLoadPermissions'));
        }
      } catch (error) {
        console.error('Error loading permissions:', error);
        ElMessage.error(t('message.failedToLoadPermissions'));
      }
    };
    
    // 打开添加权限对话框
    const openAddPermissionDialog = () => {
      isEdit.value = false;
      dialogTitle.value = t('message.addPermission');
      resetForm();
      dialogVisible.value = true;
    };
    
    // 编辑权限
    const editPermission = (permission) => {
      isEdit.value = true;
      dialogTitle.value = t('message.editPermission');
      // 复制权限数据到表单
      Object.assign(permissionForm.value, permission);
      dialogVisible.value = true;
    };
    
    // 删除权限
    const deletePermission = async (permissionId) => {
      try {
        await ElMessageBox.confirm(
          t('message.confirmDeletePermission'),
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        const response = await fetch(`/api/admin/permissions/${permissionId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          ElMessage.success(t('message.deletePermissionSuccess'));
          loadPermissions(); // 重新加载权限
        } else {
          ElMessage.error(t('message.deletePermissionFailed'));
        }
      } catch (error) {
        console.error('Error deleting permission:', error);
      }
    };
    
    // 保存权限
    const savePermission = async () => {
      try {
        await permissionFormRef.value.validate();
        
        let response;
        if (isEdit.value) {
          // 更新权限
          response = await fetch(`/api/admin/permissions/${permissionForm.value.permissionId}`, {
            method: 'PUT',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(permissionForm.value)
          });
        } else {
          // 创建权限
          response = await fetch('/api/admin/permissions', {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(permissionForm.value)
          });
        }
        
        if (response.ok) {
          ElMessage.success(isEdit.value ? t('message.updatePermissionSuccess') : t('message.addPermissionSuccess'));
          dialogVisible.value = false;
          loadPermissions(); // 重新加载权限
        } else {
          const errorData = await response.json();
          ElMessage.error(errorData.message || (isEdit.value ? t('message.updatePermissionFailed') : t('message.addPermissionFailed')));
        }
      } catch (error) {
        console.error('Error saving permission:', error);
        ElMessage.error(isEdit.value ? t('message.updatePermissionFailed') : t('message.addPermissionFailed'));
      }
    };
    
    // 重置表单
    const resetForm = () => {
      permissionForm.value = {
        permissionId: '',
        permissionName: '',
        permissionCode: '',
        permissionDescription: ''
      };
    };
    
    onMounted(() => {
      loadPermissions();
    });
    
    return {
      permissions,
      dialogVisible,
      dialogTitle,
      permissionForm,
      permissionFormRef,
      permissionRules,
      openAddPermissionDialog,
      editPermission,
      deletePermission,
      savePermission
    };
  }
};
</script>

<style scoped>
.permission-management {
  padding: 20px;
}

.permission-actions {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>